<template>
  <div class="chatContainer">
    <div class="roomWrapper" ref="roomWrapperRef">
      <div class="item" v-for="(el, index) in chatList" :key="index">
        <div v-if="el.type === 'txt'">
          {{ el.msg }}
        </div>
        <FileCom v-else :url="el.msg"></FileCom>
      </div>
    </div>
    <div class="operateBox">
      <div class="icons">
        <input type="file" id="chooseFileInput" />
        <div class="icon">
          <icon-image size="30px" />
        </div>
      </div>
      <div class="btnPosition">
        <a-button
          @click="sendMsg"
          style="background-color: rgb(3, 169, 244)"
          type="primary"
          status="danger"
          >send</a-button
        >
      </div>
      <a-textarea
        v-model="inputVal"
        placeholder="Please enter something"
        allow-clear
      />
    </div>
  </div>
</template>

<script setup>
  import { Message } from '@arco-design/web-vue';
  import { nextTick, onMounted, ref } from 'vue';
  import { fileDomain } from '@/templateDir/utils/common';
  import { updateFile } from '@/api/common';

  import Socket from './ws';

  import FileCom from '@/components/file/index.vue';

  const roomWrapperRef = ref(null);

  const chatList = ref([
    {
      msg: '阿斯顿发啥发啥大发',
      type: 'txt',
    },
  ]);

  const inputVal = ref('');

  const sendTxtMsg = (str) => {
    wbSocket.value.send(
      JSON.stringify({
        msg: str,
        type: 'txt',
      })
    );
  };

  const sendFileMsg = (url) => {
    wbSocket.value.send(
      JSON.stringify({
        msg: url,
        type: 'file',
      })
    );
  };

  const sendMsg = () => {
    if (inputVal.value?.trim()) {
      sendTxtMsg(inputVal.value);
      inputVal.value = '';
    }
  };

  const wbSocket = ref(null);

  const initUploadFile = () => {
    const domInput = document.querySelector('#chooseFileInput');
    domInput.addEventListener('change', () => {
      const file = domInput.files[0];

      if (file) {
        const formData = new FormData();
        formData.append('file', file);
        updateFile(formData)
          .then((res) => {
            const link = fileDomain + res?.data;
            sendFileMsg(link);
          })
          .catch((err) => {
            console.log(err);
          });

        // 文件已选择
        console.log('文件已选择：' + file.name);
      } else {
        // 文件未选择
        console.log('文件未选择');
      }
    });
  };

  const otherEvent = () => {
    document.addEventListener('mousemove', (event) => {
      document.title = '聊天室';
    });

    document.addEventListener('keydown', (event) => {
      if(event.metaKey && event.keyCode === 13) {
        sendMsg();
      }

      if(event.ctrlKey && event.keyCode === 13) {
        sendMsg();
      }
    });
  };

  const initWebsocket = () => {
    let loginInfo = localStorage.getItem('login-config');

    try {
      loginInfo = JSON.parse(loginInfo);
    } catch (error) {}

    wbSocket.value = new Socket({
      url: `/chatRoom/${loginInfo.username}`,
    });

    wbSocket.value.onmessage((message) => {
      if (message.data === 'ping') {
        return;
      }
      message = JSON.parse(message.data);
      if (message.type === 'txt' || message.type === 'file') {
        chatList.value.push(message);
        nextTick().then(() => {
          roomWrapperRef.value.scrollTop = 36 * chatList.value.length
        });
      }

      if (message.type !== 'ping') {
        if (document.hidden) {
          document.title = '您有一条消息待阅读';
        } else {
          document.title = '聊天室';
        }
      }
    });
  };

  onMounted(() => {
    initUploadFile();

    otherEvent();

    initWebsocket();

  });
</script>

<style lang="less" scoped>
  .chatContainer {
    width: 100vw;
    height: 100vh;
    background: rgb(41, 49, 75);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    .operateBox {
      width: 1200px;
      max-width: 80%;
      height: 200px;
      background: rgb(54, 67, 101);
      margin-top: 20px;
      border-radius: 10px;
      position: relative;
      overflow: hidden;
      .btnPosition {
        position: absolute;
        bottom: 10px;
        right: 10px;
        z-index: 10;
      }
      .icons {
        width: 40px;
        height: 40px;
        padding: 10px;
        box-sizing: border-box;
        position: relative;
        input {
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          position: absolute;
          z-index: 3;
          opacity: 0;
          cursor: pointer;
        }
        .icon {
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          position: absolute;
          z-index: 2;

          display: flex;
          align-items: center;
          justify-content: center;
        }
      }
      /deep/ .arco-textarea-wrapper {
        border: none;
        background: transparent;
      }
      /deep/ textarea {
        background: rgb(60, 68, 91);
        font-size: 16px;
        color: #fff;
        letter-spacing: 1px;
        height: 160px;
        border: 1px solid rgb(60, 68, 91);
        outline: none;
        resize: none;
        // box-shadow: rgb(18, 120, 176) 0px 0px 0px 1px inset,
        //   rgb(29, 85, 125) 0px 0px 0px 3px;
      }
    }
    .roomWrapper {
      width: 1200px;
      max-width: 80%;
      height: 500px;
      background: rgb(54, 67, 101);
      padding: 20px;
      border-radius: 10px;
      overflow: auto;
      .item {
        color: #fff;
        margin-bottom: 20px;
      }
    }
  }
</style>
